<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>一键出题 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-4 py-2 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">一键出题</h2>
        </div>
        <p class="text-gray-500 mt-1">多种出题方式满足您的需求，支持描述检索、PDF上传、导入试卷和选择题库</p>
      </div>

      <!-- 出题模式选择 - 新增两种模式 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <h3 class="font-bold text-lg mb-4">选择出题模式</h3>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div id="desc-mode" class="border-2 border-primary rounded-xl p-5 cursor-pointer bg-primary/5">
            <div class="flex items-center mb-3">
              <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                <i class="fa fa-file-text-o"></i>
              </div>
              <h4 class="font-medium">描述性语言出题</h4>
            </div>
            <p class="text-gray-500 text-sm">通过输入知识点描述、难度要求等信息，从题库中检索并生成试题</p>
          </div>

          <div id="pdf-mode" class="border-2 border-gray-200 rounded-xl p-5 cursor-pointer hover:border-primary/50 transition-colors">
            <div class="flex items-center mb-3">
              <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 mr-3">
                <i class="fa fa-file-pdf-o"></i>
              </div>
              <h4 class="font-medium">PDF上传出题</h4>
            </div>
            <p class="text-gray-500 text-sm">上传PDF文档，系统将基于文档内容生成相关试题</p>
          </div>

          <!-- 新增：导入已有试卷 -->
          <div id="import-mode" class="border-2 border-gray-200 rounded-xl p-5 cursor-pointer hover:border-primary/50 transition-colors">
            <div class="flex items-center mb-3">
              <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 mr-3">
                <i class="fa fa-upload"></i>
              </div>
              <h4 class="font-medium">导入已有试卷</h4>
            </div>
            <p class="text-gray-500 text-sm">导入系统支持的试卷格式文件(.xml, .json)，快速复用已有试卷</p>
          </div>

          <!-- 新增：选择题库出题 -->
          <div id="bank-mode" class="border-2 border-gray-200 rounded-xl p-5 cursor-pointer hover:border-primary/50 transition-colors">
            <div class="flex items-center mb-3">
              <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 mr-3">
                <i class="fa fa-check-square"></i>
              </div>
              <h4 class="font-medium">智能识别试卷</h4>
            </div>
            <p class="text-gray-500 text-sm">智能识别题目类型，生成新试卷</p>
          </div>
        </div>
      </div>

      <!-- 描述性语言输入区 -->
      <div id="desc-content" class="mb-6">
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
          <h3 class="font-bold text-lg mb-4">输入出题描述</h3>
          <div>
            <label for="question-desc" class="block text-sm font-medium text-gray-700 mb-2">请描述需要生成的试题范围、知识点、难度等信息</label>
            <textarea id="question-desc" rows="4" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" placeholder="例如：生成一套高中数学函数章节的测试题，包含基础到中等难度，重点考察二次函数和三角函数..."></textarea>
            <p class="text-xs text-gray-500 mt-2">提示：描述越详细，生成的试题越符合您的需求</p>
          </div>
        </div>
      </div>

      <!-- PDF上传区 (默认隐藏) -->
      <div id="pdf-content" class="mb-6 hidden">
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
          <h3 class="font-bold text-lg mb-4">上传PDF文档</h3>
          <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-primary/50 transition-colors cursor-pointer">
            <input type="file" id="pdf-upload" class="hidden" accept=".pdf">
            <label for="pdf-upload" class="cursor-pointer">
              <div class="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 mx-auto mb-4">
                <i class="fa fa-cloud-upload text-2xl"></i>
              </div>
              <h4 class="font-medium mb-1">点击或拖拽PDF文件到此处</h4>
              <p class="text-sm text-gray-500">支持上传不超过10MB的PDF文件</p>
            </label>
          </div>

          <div id="pdf-preview" class="hidden mt-4 p-3 bg-gray-50 rounded-lg">
            <div class="flex items-center">
              <i class="fa fa-file-pdf-o text-red-500 mr-3 text-xl"></i>
              <div class="flex-1">
                <p id="pdf-filename" class="font-medium truncate">sample-document.pdf</p>
                <p class="text-xs text-gray-500">2.4 MB</p>
              </div>
              <button id="remove-pdf" class="text-gray-400 hover:text-red-500">
                <i class="fa fa-times"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

            <!-- 新增：导入已有试卷区域 -->
      <div id="import-content" class="mb-6 hidden">
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
          <h3 class="font-bold text-lg mb-4">导入已有试卷</h3>

          <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-primary/50 transition-colors">
              <input type="file" id="exam-upload" class="hidden" accept=".xml,.json">
              <label for="exam-upload" class="cursor-pointer block">
                <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mx-auto mb-3">
                  <i class="fa fa-upload text-xl"></i>
                </div>
                <h4 class="font-medium mb-1">点击上传试卷文件</h4>
                <p class="text-sm text-gray-500">支持 XML 或 JSON 格式</p>
              </label>
          </div>

          <div id="exam-preview" class="hidden mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <i class="fa fa-check-circle text-green-500 mr-2"></i>
                  <span class="font-medium" id="exam-filename">试卷文件</span>
                </div>
                <button id="remove-exam" class="text-gray-400 hover:text-red-500">
                  <i class="fa fa-times"></i>
                </button>
              </div>
          </div>
        </div>
      </div>

      <!-- 新增：智能识别试卷区域 -->
      <div id="bank-content" class="mb-6 hidden">
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
          <h3 class="font-bold text-lg mb-4">智能识别试卷</h3>
            <div>
             <label for="question-text" class="block text-sm font-medium text-gray-700 mb-2">请输入试题内容或上传试卷图片</label>
             <textarea id="question-text" rows="4" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" placeholder="请输入试题内容，系统将自动识别题目类型并生成试卷..."></textarea>
            </div>
        </div>
      </div>

      <!-- 试题数量设置 -->
      <div id="quantity-settings" class="bg-white rounded-xl p-5 card-shadow mb-6">
        <h3 class="font-bold text-lg mb-4">试题数量设置</h3>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label for="single-choice" class="block text-sm font-medium text-gray-700 mb-1">选择题数量</label>
            <div class="flex items-center">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-l-lg flex items-center justify-center hover:bg-gray-50" data-target="single-choice" data-action="decrease">
                <i class="fa fa-minus text-sm"></i>
              </button>
              <input type="number" id="single-choice" min="0" max="50" value="2" class="w-16 h-10 border-t border-b border-gray-300 text-center focus:outline-none focus:ring-1 focus:ring-primary">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-r-lg flex items-center justify-center hover:bg-gray-50" data-target="single-choice" data-action="increase">
                <i class="fa fa-plus text-sm"></i>
              </button>
            </div>
          </div>

          <div>
            <label for="multiple-choice" class="block text-sm font-medium text-gray-700 mb-1">多选题数量</label>
            <div class="flex items-center">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-l-lg flex items-center justify-center hover:bg-gray-50" data-target="multiple-choice" data-action="decrease">
                <i class="fa fa-minus text-sm"></i>
              </button>
              <input type="number" id="multiple-choice" min="0" max="30" value="2" class="w-16 h-10 border-t border-b border-gray-300 text-center focus:outline-none focus:ring-1 focus:ring-primary">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-r-lg flex items-center justify-center hover:bg-gray-50" data-target="multiple-choice" data-action="increase">
                <i class="fa fa-plus text-sm"></i>
              </button>
            </div>
          </div>

          <div>
            <label for="fill-blank" class="block text-sm font-medium text-gray-700 mb-1">填空题数量</label>
            <div class="flex items-center">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-l-lg flex items-center justify-center hover:bg-gray-50" data-target="fill-blank" data-action="decrease">
                <i class="fa fa-minus text-sm"></i>
              </button>
              <input type="number" id="fill-blank" min="0" max="20" value="2" class="w-16 h-10 border-t border-b border-gray-300 text-center focus:outline-none focus:ring-1 focus:ring-primary">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-r-lg flex items-center justify-center hover:bg-gray-50" data-target="fill-blank" data-action="increase">
                <i class="fa fa-plus text-sm"></i>
              </button>
            </div>
          </div>

          <div>
            <label for="short-answer" class="block text-sm font-medium text-gray-700 mb-1">简答题数量</label>
            <div class="flex items-center">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-l-lg flex items-center justify-center hover:bg-gray-50" data-target="short-answer" data-action="decrease">
                <i class="fa fa-minus text-sm"></i>
              </button>
              <input type="number" id="short-answer" min="0" max="10" value="2" class="w-16 h-10 border-t border-b border-gray-300 text-center focus:outline-none focus:ring-1 focus:ring-primary">
              <button type="button" class="quantity-btn w-10 h-10 border border-gray-300 rounded-r-lg flex items-center justify-center hover:bg-gray-50" data-target="short-answer" data-action="increase">
                <i class="fa fa-plus text-sm"></i>
              </button>
            </div>
          </div>

          <div class="flex items-end">
            <div class="p-3 bg-gray-50 rounded-lg w-full">
              <p class="text-sm font-medium mb-1">总题数: <span id="total-questions" class="text-primary">17</span></p>
              <p class="text-xs text-gray-500">请至少选择一种题型并设置数量</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 生成的试题预览 -->
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
          <div class="flex justify-between items-center mb-4">
            <h3 class="font-bold text-lg">试题预览</h3>
            <span class="text-sm text-gray-500">点击试题可进行编辑</span>
          </div>

          <div id="question-preview" class="space-y-6">
            <!-- 这里会动态生成试题预览 -->
            <div class="text-center text-gray-500 py-8">
              <i class="fa fa-file-text-o text-4xl mb-4"></i>
              <p>暂无试题，请先生成试题</p>
            </div>
          </div>
        </div>

      <!-- 操作按钮 -->
      <div class="flex flex-col sm:flex-row justify-center gap-4 mb-6">
          <!-- 生成试题按钮 -->
        <button id="generate-btn" class="bg-accent text-white px-8 py-3 rounded-lg transition-all duration-300 hover:bg-accent/90 active:bg-accent/80 text-lg font-medium flex items-center">
          <i class="fa fa-magic mr-2"></i> 生成试题
        </button>
        <button class="btn-primary flex-1 sm:flex-none min-w-[140px] justify-center py-3">
          <i class="fa fa-save mr-2"></i> 保存到题库
        </button>
        <button id="clear-all-btn" class="btn-danger flex-1 sm:flex-none min-w-[140px] justify-center py-3">
          <i class="fa fa-times mr-2"></i> 删除试题
        </button>
      </div>
    </div>
  </main>

  <!-- 保存到题库弹窗 -->
  <div id="save-to-bank-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-md mx-4">
      <div class="flex justify-between items-center mb-4">
        <h3 class="font-bold text-lg text-neutral-dark">保存到题库</h3>
        <button id="close-modal" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <form id="save-to-bank-form" class="space-y-4">
      <!-- 选择学科 -->
        <div>
          <label for="subject-input" class="block text-sm font-medium text-gray-700 mb-1">输入学科</label>
            <input
                type="text"
                id="subject-input"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 transition-colors"
                placeholder="请输入学科名称"
                required
            >
            <p class="text-xs text-gray-500 mt-1">请输入您要学习的学科名称</p >
        </div>

        <!-- 选择年级 -->
        <div>
          <label for="grade-select" class="block text-sm font-medium text-gray-700 mb-1">选择年级</label>
          <select id="grade-select" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
            <option value="">请选择年级</option>-->
            {% for grade in grades %}
            <option value="{{ grade }}">{{ grade }}</option>-->
            {% endfor %}
<!--            <option value="">请选择年级</option>-->
<!--            <option value="grade7">七年级</option>-->
<!--            <option value="grade8">八年级</option>-->
<!--            <option value="grade9">九年级</option>-->
<!--            <option value="grade10">高一年级</option>-->
<!--            <option value="grade11">高二年级</option>-->
<!--            <option value="grade12">高三年级</option>-->
          </select>
        </div>

        <!-- 输入天数 -->
        <div>
          <label for="validity-select" class="block text-sm font-medium text-gray-700 mb-1">请输入天数</label>
          <input
              id="validity-select"
              type="number"
              placeholder="请输入天数"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
              required
            >
        </div>

        <!-- 输入知识点 -->
        <div>
          <label for="type-select" class="block text-sm font-medium text-gray-700 mb-1">请输入知识点</label>
          <input
            id="type-select"
            type="text"
            placeholder="请输入知识点（如：加减法）"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
            required
          >
        </div>

        <!-- 操作按钮 -->
        <div class="flex space-x-3 pt-2">
          <button type="button" id="cancel-save" class="flex-1 btn-secondary">取消</button>
          <button type="submit" class="flex-1 btn-primary">确定添加</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

  <script>
    //全局变量
    // 全局重置生成按钮状态的函数
    function resetGenerateButton() {
        const generateBtn = document.getElementById('generate-btn');
        if (generateBtn) {
            generateBtn.innerHTML = '<i class="fa fa-magic mr-2"></i> 生成试题';
            generateBtn.disabled = false;
        }
    }
    // pdf文件
    var pdf_file = null;
    // 当前考试内容
    let currentExamContent = null;
    // 识别的考试内容
    let identifiedExamContent = null;

    // 角色切换功能
    const setupRoleSwitch = () => {
        const teacherTab = document.getElementById('teacher-tab');
        const studentTab = document.getElementById('student-tab');
        const teacherNav = document.getElementById('teacher-nav');
        const studentNav = document.getElementById('student-nav');

        teacherTab.addEventListener('click', () => {
            // 更新标签样式
            teacherTab.classList.add('bg-primary', 'text-white');
            teacherTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
            studentTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
            studentTab.classList.remove('bg-primary', 'text-white');

            // 显示教师导航，隐藏学生导航
            teacherNav.classList.remove('hidden');
            studentNav.classList.add('hidden');
        });

    };

    var model_num = 1;

    // 出题模式切换 - 新增两种模式的切换逻辑
    const setupModeSwitch = () => {
        const descMode = document.getElementById('desc-mode');
        const pdfMode = document.getElementById('pdf-mode');
        const importMode = document.getElementById('import-mode');
        const bankMode = document.getElementById('bank-mode');

        const descContent = document.getElementById('desc-content');
        const pdfContent = document.getElementById('pdf-content');
        const importContent = document.getElementById('import-content');
        const bankContent = document.getElementById('bank-content');

        // 重置所有模式样式
        const resetAllModes = () => {
            [descMode, pdfMode, importMode, bankMode].forEach(mode => {
                mode.classList.add('border-gray-200');
                mode.classList.remove('border-primary', 'bg-primary/5');
                // 更新图标颜色
                const icon = mode.querySelector('.fa');
                icon.classList.remove('text-primary');
                icon.classList.add('text-gray-500');
            });

            [descContent, pdfContent, importContent, bankContent].forEach(content => {
                content.classList.add('hidden');
            });
        };

        descMode.addEventListener('click', () => {
            resetAllModes();
            // 更新描述模式样式
            model_num = 1;
            descMode.classList.add('border-primary', 'bg-primary/5');
            descMode.classList.remove('border-gray-200');
            // 更新图标颜色
            const icon = descMode.querySelector('.fa');
            icon.classList.remove('text-gray-500');
            icon.classList.add('text-primary');
            // 显示描述内容
            descContent.classList.remove('hidden');
            document.getElementById('quantity-settings').classList.remove('hidden');
            document.getElementById('question-preview').innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa fa-file-text-o text-4xl mb-4"></i>
                    <p>暂无试题，请先生成试题</p>
                </div>
            `;
        });

        pdfMode.addEventListener('click', () => {
            resetAllModes();
            // 更新PDF模式样式
            model_num = 2;
            pdfMode.classList.add('border-primary', 'bg-primary/5');
            pdfMode.classList.remove('border-gray-200');
            // 更新图标颜色
            const icon = pdfMode.querySelector('.fa');
            icon.classList.remove('text-gray-500');
            icon.classList.add('text-primary');
            // 显示PDF内容
            pdfContent.classList.remove('hidden');
            document.getElementById('quantity-settings').classList.remove('hidden');
            document.getElementById('question-preview').innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa fa-file-text-o text-4xl mb-4"></i>
                    <p>暂无试题，请先生成试题</p>
                </div>
            `;
        });

        // 新增：导入试卷模式
        importMode.addEventListener('click', () => {
            resetAllModes();
            model_num = 3;
            document.getElementById('quantity-settings').classList.add('hidden');
            // 更新导入模式样式
            importMode.classList.add('border-primary', 'bg-primary/5');
            importMode.classList.remove('border-gray-200');
            // 更新图标颜色
            const icon = importMode.querySelector('.fa');
            icon.classList.remove('text-gray-500');
            icon.classList.add('text-primary');
            // 显示导入内容
            importContent.classList.remove('hidden');
            document.getElementById('question-preview').innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa fa-file-text-o text-4xl mb-4"></i>
                    <p>暂无试题，请先生成试题</p>
                </div>
            `;
        });

        // 新增：智能识别模式
        bankMode.addEventListener('click', () => {
            resetAllModes();
            model_num = 4;
            document.getElementById('quantity-settings').classList.add('hidden');
            // 更新智能识别模式样式
            bankMode.classList.add('border-primary', 'bg-primary/5');
            bankMode.classList.remove('border-gray-200');
            // 更新图标颜色
            const icon = bankMode.querySelector('.fa');
            icon.classList.remove('text-gray-500');
            icon.classList.add('text-primary');
            // 显示智能识别内容
            bankContent.classList.remove('hidden');
            document.getElementById('question-preview').innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa fa-file-text-o text-4xl mb-4"></i>
                    <p>暂无试题，请先生成试题</p>
                </div>
            `;
        });
    };

    const calculateTotal = () => {
        const single = parseInt(document.getElementById('single-choice').value) || 0;
        const multiple = parseInt(document.getElementById('multiple-choice').value) || 0;
        const fillBlank = parseInt(document.getElementById('fill-blank').value) || 0;
        const shortAnswer = parseInt(document.getElementById('short-answer').value) || 0;

        const total = single + multiple + fillBlank + shortAnswer;
        document.getElementById('total-questions').textContent = total;

        return total;
    };

    // 数量调整功能
    const setupQuantityControls = () => {
        const quantityBtns = document.querySelectorAll('.quantity-btn');
        // 绑定按钮事件
        quantityBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const targetId = btn.getAttribute('data-target');
                const action = btn.getAttribute('data-action');
                const inputEl = document.getElementById(targetId);

                let value = parseInt(inputEl.value) || 0;
                const min = parseInt(inputEl.min) || 0;
                const max = parseInt(inputEl.max) || 100;

                if (action === 'increase' && value < max) {
                    value++;
                } else if (action === 'decrease' && value > min) {
                    value--;
                }

                inputEl.value = value;
                calculateTotal();
            });
        });

        // 输入框变化时重新计算
        document.querySelectorAll('input[type="number"]').forEach(input => {
            input.addEventListener('change', () => {
                // 确保值在有效范围内
                const value = parseInt(input.value) || 0;
                const min = parseInt(input.min) || 0;
                const max = parseInt(input.max) || 100;

                if (value < min) input.value = min;
                if (value > max) input.value = max;

                calculateTotal();
            });
        });

        // 初始化计算
        calculateTotal();
    };

    // PDF上传功能
    const setupPdfUpload = () => {
        const pdfUpload = document.getElementById('pdf-upload');
        const pdfPreview = document.getElementById('pdf-preview');
        const pdfFilename = document.getElementById('pdf-filename');
        const removePdf = document.getElementById('remove-pdf');

        pdfUpload.addEventListener('change', (e) => {
            if (e.target.files && e.target.files[0]) {
                pdf_file = e.target.files[0];
                pdfFilename.textContent = pdf_file.name;
                pdfPreview.classList.remove('hidden');
            }
        });

        removePdf.addEventListener('click', () => {
            pdfUpload.value = '';
            pdfPreview.classList.add('hidden');
        });
    };

    // 上传PDF文件的函数
    async function uploadPdfToBackend(file, single_choice, multiple_choice, fill_blank, short_answer) {
        const formData = new FormData();
        formData.append('pdf_file', file);
        formData.append('single_choice', single_choice);
        formData.append('multiple_choice', multiple_choice);
        formData.append('fill_blank', fill_blank);
        formData.append('short_answer', short_answer);

        try {
            const response = await fetch('/pdf_questions', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            if (result.success) {
                // 更新试题预览区域
                updateQuestionPreview(result.data);
                showNotification('试题生成成功！', 'success');

                // 滚动到试题预览区域
                document.querySelector('.bg-white.rounded-xl.p-5.card-shadow.mb-6:nth-last-of-type(2)').scrollIntoView({
                    behavior: 'smooth'
                });
            } else {
                showNotification('生成试题失败：' + result.error, 'error');
            }
        } catch (error) {
            console.error('PDF上传失败:', error);
            showNotification('PDF上传失败，请重试', 'error');
        }
    }

    // 试卷导入功能
    const setupExamImport = () => {
        const examUpload = document.getElementById('exam-upload');
        const examPreview = document.getElementById('exam-preview');
        const examFilename = document.getElementById('exam-filename');
        const removeExam = document.getElementById('remove-exam');

        examUpload.addEventListener('change', (e) => {
            if (e.target.files && e.target.files[0]) {
                const file = e.target.files[0];
                examFilename.textContent = file.name;
                examPreview.classList.remove('hidden');
                // 上传文件
                uploadExamFile(file);
            }
        });

        removeExam.addEventListener('click', () => {
            examUpload.value = '';
            examPreview.classList.add('hidden');
            currentExamContent = null;
        });

        // 最近导入试卷的导入按钮
        document.querySelectorAll('.space-y-2 .text-primary').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const filename = btn.closest('div').querySelector('p').textContent;
                examFilename.textContent = filename;
                examPreview.classList.remove('hidden');
            });
        });
    };

    // 上传试卷文件
    function uploadExamFile(file) {
        const formData = new FormData();
        formData.append('file', file);

        fetch('/api/upload_exam', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    currentExamContent = data.exam_info.content;
                    showNotification('试卷上传成功！', 'success');
                } else {
                    showNotification('试卷上传失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('上传失败:', error);
                showNotification('上传失败，请重试', 'error');
            });
    }

    // 智能识别试卷功能
    // 智能识别试卷功能
    function identifyQuestionsFromText() {
        const questionText = document.getElementById('question-text').value.trim();

        if (!questionText) {
            showNotification('请输入试题内容', 'error');
            // 重置按钮状态
            resetGenerateButton();
            return;
        }

        const generateBtn = document.getElementById('generate-btn');
        generateBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 识别中...';
        generateBtn.disabled = true;

        fetch('/api/identify_questions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                text_content: questionText
            })
        })
            .then(response => response.json())
            .then(data => {
                // 重置按钮状态
                resetGenerateButton();

                if (data.success) {
                    identifiedExamContent = data.exam_info;
                    // 直接显示识别结果
                    updateQuestionPreview(convertExamData(identifiedExamContent));
                    showNotification(`成功识别 ${data.exam_info.questions.length} 道题目`, 'success');
                } else {
                    showNotification('识别失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('识别失败:', error);
                // 重置按钮状态
                resetGenerateButton();
                showNotification('识别失败，请重试', 'error');
            });
    }

    // 生成试卷预览
    function generateExamPreview(examContent) {
        fetch('/api/generate_exam', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                exam_content: examContent
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateQuestionPreview(convertExamData(data.exam_preview));
                    showNotification('试卷预览生成成功！', 'success');
                } else {
                    showNotification('生成预览失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('生成预览失败:', error);
                showNotification('生成预览失败，请重试', 'error');
            });
    }

    // 转换试卷数据格式以适应预览
    function convertExamData(examData) {
        const result = {
            "选择题": [],
            "多选题": [],
            "填空题": [],
            "简答题": []
        };

        if (!examData || (!examData.questions && !examData.content)) {
            return result;
        }

        let questionsData = examData.questions || examData.content?.questions;

        if (questionsData) {
            Object.entries(questionsData).forEach(([type, questions]) => {
                if (questions && questions.length > 0) {
                    questions.forEach(question => {
                        switch (type) {
                            case '选择题':
                            case '单选题':
                                result["选择题"].push({
                                    "题目": question.题目 || '题目内容',
                                    "选项": question.选项 || {},
                                    "正确答案": question.正确答案 || '暂无答案'
                                });
                                break;
                            case '多选题':
                                result["多选题"].push({
                                    "题目": question.题目 || '题目内容',
                                    "选项": question.选项 || {},
                                    "正确答案": question.正确答案 || '暂无答案'
                                });
                                break;
                            case '填空题':
                                result["填空题"].push({
                                    "题目": question.题目 || '题目内容',
                                    "正确答案": question.正确答案 || '暂无答案'
                                });
                                break;
                            case '简答题':
                                result["简答题"].push({
                                    "题目": question.题目 || '题目内容',
                                    "正确答案": question.正确答案 || '暂无答案'
                                });
                                break;
                        }
                    });
                }
            });
        }

        return result;
    }

    // 显示通知
    function showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg max-w-sm transition-all duration-300 transform translate-x-full ${
            type === 'success' ? 'bg-green-100 text-green-800 border border-green-200' :
            type === 'error' ? 'bg-red-100 text-red-800 border border-red-200' :
            'bg-blue-100 text-blue-800 border border-blue-200'
        }`;

        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fa ${
                    type === 'success' ? 'fa-check-circle' :
                    type === 'error' ? 'fa-exclamation-circle' :
                    'fa-info-circle'
                } mr-2"></i>
                <span>${message}</span>
            </div>
        `;

        document.body.appendChild(notification);

        // 显示通知
        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 10);

        // 3秒后自动移除
        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    // 生成试题按钮功能
    // 生成试题按钮功能
    const setupGenerateButton = () => {
        const generateBtn = document.getElementById('generate-btn');

        // 添加重置按钮状态的函数
        const resetGenerateButton = () => {
            generateBtn.innerHTML = '<i class="fa fa-magic mr-2"></i> 生成试题';
            generateBtn.disabled = false;
        };

        generateBtn.addEventListener('click', async () => {
            // 显示加载状态
            generateBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 生成中...';
            generateBtn.disabled = true;

            try {
                // 获取提示词
                const prompt = document.getElementById('question-desc').value;
                // 选择题数量
                const single_choice = document.getElementById('single-choice').value;
                // 多选题数量
                const multiple_choice = document.getElementById('multiple-choice').value;
                // 填空题
                const fill_blank = document.getElementById('fill-blank').value;
                // 简答题
                const short_answer = document.getElementById('short-answer').value;

                // 构建请求数据
                const requestData = {
                    prompt: prompt,
                    question_types: {
                        single_choice: parseInt(single_choice) || 0,
                        multiple_choice: parseInt(multiple_choice) || 0,
                        fill_blank: parseInt(fill_blank) || 0,
                        short_answer: parseInt(short_answer) || 0
                    }
                };

                if (model_num == 1) {
                    // 调用后端generate接口
                    const response = await fetch('/generate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    });
                    const result = await response.json();
                    if (result.success) {
                        // 更新试题预览区域
                        updateQuestionPreview(result.data);
                        showNotification('试题生成成功！', 'success');

                        // 滚动到试题预览区域
                        document.querySelector('.bg-white.rounded-xl.p-5.card-shadow.mb-6:nth-last-of-type(2)').scrollIntoView({
                            behavior: 'smooth'
                        });
                    } else {
                        showNotification('生成试题失败：' + result.error, 'error');
                    }
                    // 重置按钮状态
                    resetGenerateButton();

                } else if (model_num == 2) {
                    // 调用后端pdf_questions接口
                    await uploadPdfToBackend(pdf_file, single_choice, multiple_choice, fill_blank, short_answer);
                    // 重置按钮状态
                    resetGenerateButton();

                } else if (model_num == 3) {
                    // 导入模式
                    if (currentExamContent) {
                        await generateExamPreview(currentExamContent);
                        // 重置按钮状态
                        resetGenerateButton();
                    } else {
                        showNotification('请先上传试卷文件', 'error');
                        resetGenerateButton();
                    }
                } else if (model_num == 4) {
                    // 智能识别模式
                    await identifyQuestionsFromText();
                    // 注意：identifyQuestionsFromText 内部已经处理了按钮重置
                }

            } catch (error) {
                console.error('请求失败:', error);
                showNotification('请求失败，请检查网络连接', 'error');
                resetGenerateButton();
            }
        });
    };

    // 更新试题预览的函数
    const generateSingleChoiceHtml = (questions) => {
        let html = `
            <div>
                <h4 class="font-medium text-primary mb-3 flex items-center">
                    <i class="fa fa-list-ul mr-2"></i> 选择题 (${questions.length}题)
                </h4>
                <div class="space-y-4 pl-4 border-l-2 border-primary/20">
        `;

        questions.forEach((question, index) => {
            html += `
                <div class="p-3 border border-gray-100 rounded-lg hover:border-primary/30 transition-colors relative" data-question-id="single-${index}">
                    <button class="delete-btn absolute top-2 right-2 text-gray-400 hover:text-red-500 transition-colors" data-type="single" data-index="${index}">
                        <i class="fa fa-times"></i>
                    </button>
                    <p class="font-medium mb-2 pr-6">${index + 1}. ${question.题目}</p>
                    <div class="space-y-1 ml-4">
            `;

            // 生成选项
            if (question.选项 && typeof question.选项 === 'object') {
                Object.entries(question.选项).forEach(([key, value]) => {
                    html += `
                        <div class="flex items-center">
                            <input type="radio" id="opt${index}-${key}" name="q${index}" class="mr-2">
                            <label for="opt${index}-${key}">${key}. ${value}</label>
                        </div>
                    `;
                });
            }

            html += `
                    </div>
                    <div class="mt-2 text-sm text-green-600">
                        <strong>答案：</strong>${question.正确答案}
                    </div>
                </div>
            `;
        });

        html += `
                </div>
            </div>
        `;

        return html;
    };

    // 多选题生成
    const generateMultiChoiceHtml = (questions) => {
        let html = `
            <div>
                <h4 class="font-medium text-primary mb-3 flex items-center">
                    <i class="fa fa-check-square-o mr-2"></i> 多选题 (${questions.length}题)
                </h4>
                <div class="space-y-4 pl-4 border-l-2 border-primary/20">
        `;

        questions.forEach((question, index) => {
            html += `
                <div class="p-3 border border-gray-100 rounded-lg hover:border-primary/30 transition-colors relative" data-question-id="multi-${index}">
                    <button class="delete-btn absolute top-2 right-2 text-gray-400 hover:text-red-500 transition-colors" data-type="multi" data-index="${index}">
                        <i class="fa fa-times"></i>
                    </button>
                    <p class="font-medium mb-2 pr-6">${index + 1}. ${question.题目}</p>
                    <div class="space-y-1 ml-4">
            `;

            // 生成选项
            if (question.选项 && typeof question.选项 === 'object') {
                Object.entries(question.选项).forEach(([key, value]) => {
                    html += `
                        <div class="flex items-center">
                            <input type="checkbox" id="mopt${index}-${key}" class="mr-2">
                            <label for="mopt${index}-${key}">${key}. ${value}</label>
                        </div>
                    `;
                });
            }

            html += `
                    </div>
                    <div class="mt-2 text-sm text-green-600">
                        <strong>答案：</strong>${question.正确答案}
                    </div>
                </div>
            `;
        });

        html += `
                </div>
            </div>
        `;

        return html;
    };

    // 填空题生成
    const generateFillBlankHtml = (questions) => {
        let html = `
            <div>
                <h4 class="font-medium text-primary mb-3 flex items-center">
                    <i class="fa fa-pencil-square-o mr-2"></i> 填空题 (${questions.length}题)
                </h4>
                <div class="space-y-4 pl-4 border-l-2 border-primary/20">
        `;

        questions.forEach((question, index) => {
            html += `
                <div class="p-3 border border-gray-100 rounded-lg hover:border-primary/30 transition-colors relative" data-question-id="fill-${index}">
                    <button class="delete-btn absolute top-2 right-2 text-gray-400 hover:text-red-500 transition-colors" data-type="fill" data-index="${index}">
                        <i class="fa fa-times"></i>
                    </button>
                    <p class="font-medium mb-2 pr-6">${index + 1}. ${question.题目}</p>
                    <div class="mt-2">
                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary" placeholder="请输入答案">
                    </div>
                    <div class="mt-2 text-sm text-green-600">
                        <strong>答案：</strong>${question.正确答案}
                    </div>
                </div>
            `;
        });

        html += `
                </div>
            </div>
        `;

        return html;
    };

    // 简答题生成
    const generateShortAnswerHtml = (questions) => {
        let html = `
            <div>
                <h4 class="font-medium text-primary mb-3 flex items-center">
                    <i class="fa fa-comment-o mr-2"></i> 简答题 (${questions.length}题)
                </h4>
                <div class="space-y-4 pl-4 border-l-2 border-primary/20">
        `;

        questions.forEach((question, index) => {
            html += `
                <div class="p-3 border border-gray-100 rounded-lg hover:border-primary/30 transition-colors relative" data-question-id="short-${index}">
                    <button class="delete-btn absolute top-2 right-2 text-gray-400 hover:text-red-500 transition-colors" data-type="short" data-index="${index}">
                        <i class="fa fa-times"></i>
                    </button>
                    <p class="font-medium mb-2 pr-6">${index + 1}. ${question.题目}</p>
                    <div class="mt-2">
                        <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary" rows="3" placeholder="请输入答案"></textarea>
                    </div>
                    <div class="mt-2 text-sm text-green-600">
                        <strong>参考答案：</strong>${question.正确答案}
                    </div>
                </div>
            `;
        });

        html += `
                </div>
            </div>
        `;

        return html;
    };

    // 添加删除按钮事件处理
    const setupDeleteButtons = () => {
        document.addEventListener('click', (e) => {
            if (e.target.closest('.delete-btn')) {
                const deleteBtn = e.target.closest('.delete-btn');
                const questionType = deleteBtn.getAttribute('data-type');
                const questionIndex = parseInt(deleteBtn.getAttribute('data-index'));

                // 类型映射
                const typeMap = {
                    'single': '选择题',
                    'multi': '多选题',
                    'fill': '填空题',
                    'short': '简答题'
                };

                const dataKey = typeMap[questionType];

                if (confirm('确定要删除这道题吗？')) {
                    if (window.generatedQuestions && window.generatedQuestions[dataKey]) {
                        // 删除题目
                        window.generatedQuestions[dataKey].splice(questionIndex, 1);

                        // 重新渲染
                        updateQuestionPreview(window.generatedQuestions);
                    } else {
                        console.error('删除失败：数据不存在');
                        console.log('数据键:', dataKey);
                        console.log('完整数据:', window.generatedQuestions);
                    }
                }
            }
        });
    };

    // 修改updateQuestionPreview函数，保存生成的数据
    const updateQuestionPreview = (data) => {
        // 保存生成的数据到全局变量
        window.generatedQuestions = data;

        const previewContainer = document.getElementById('question-preview');

        // 清空现有预览内容
        previewContainer.innerHTML = '';

        // 生成选择题预览
        if (data.选择题 && data.选择题.length > 0) {
            const singleChoiceHtml = generateSingleChoiceHtml(data.选择题);
            previewContainer.innerHTML += singleChoiceHtml;
        }

        // 生成多选题预览
        if (data.多选题 && data.多选题.length > 0) {
            const multiChoiceHtml = generateMultiChoiceHtml(data.多选题);
            previewContainer.innerHTML += multiChoiceHtml;
        }

        // 生成填空题预览
        if (data.填空题 && data.填空题.length > 0) {
            const fillBlankHtml = generateFillBlankHtml(data.填空题);
            previewContainer.innerHTML += fillBlankHtml;
        }

        // 生成简答题预览
        if (data.简答题 && data.简答题.length > 0) {
            const shortAnswerHtml = generateShortAnswerHtml(data.简答题);
            previewContainer.innerHTML += shortAnswerHtml;
        }

        // 如果没有题目，显示提示信息
        if (previewContainer.innerHTML === '') {
            previewContainer.innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa fa-file-text-o text-4xl mb-4"></i>
                    <p>暂无试题，请先生成试题</p>
                </div>
            `;
        }
    };

    const setupClearAll = () => {
        const clearBtn = document.getElementById('clear-all-btn');
        const questionPreview = document.getElementById('question-preview');

        clearBtn.addEventListener('click', () => {
            // 确认对话框
            if (confirm('确定要删除所有生成的试题吗？此操作不可恢复。')) {
                // 清空试题预览区域
                questionPreview.innerHTML = `
                    <div class="text-center text-gray-500 py-8">
                        <i class="fa fa-file-text-o text-4xl mb-4"></i>
                        <p>暂无试题，请先生成试题</p>
                    </div>
                `;

                // 重置数量选择器为默认值
                document.getElementById('single-choice').value = 2;
                document.getElementById('multiple-choice').value = 2;
                document.getElementById('fill-blank').value = 2;
                document.getElementById('short-answer').value = 2;

                // 重新计算总题数
                calculateTotal();

                // 重置导入的试卷内容
                currentExamContent = null;
                const examUpload = document.getElementById('exam-upload');
                const examPreview = document.getElementById('exam-preview');
                if (examUpload) {
                    examUpload.value = '';
                }
                if (examPreview) {
                    examPreview.classList.add('hidden');
                }

                // 重置智能识别内容
                identifiedExamContent = null;
                const questionText = document.getElementById('question-text');
                if (questionText) {
                    questionText.value = '';
                }
            }
        });
    };

    // 初始化保存到题库弹窗功能
    const setupSaveToBankModal = () => {
        // 获取弹窗相关元素
        const saveBtn = document.querySelector('.btn-primary:has(.fa-save)');
        const modal = document.getElementById('save-to-bank-modal');
        const closeBtn = document.getElementById('close-modal');
        const cancelBtn = document.getElementById('cancel-save');
        const saveForm = document.getElementById('save-to-bank-form');

        // 打开弹窗
        saveBtn.addEventListener('click', () => {
            // 先判断是否有生成的试题
            const hasQuestions = document.querySelector('#question-preview .p-3.border') !== null;
            if (!hasQuestions) {
                showNotification('请先生成试题后再保存到题库', 'error');
                return;
            }
            modal.classList.remove('hidden');
            // 禁止页面滚动
            document.body.style.overflow = 'hidden';
        });

        // 关闭弹窗（多种关闭方式）
        const closeModal = () => {
            modal.classList.add('hidden');
            // 恢复页面滚动
            document.body.style.overflow = '';
            // 重置表单
            saveForm.reset();
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        // 点击弹窗外部关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) closeModal();
        });

        // 表单提交处理
        saveForm.addEventListener('submit', async (e) => {
          e.preventDefault();

          const saveData = {
            savedata:window.generatedQuestions,
            subject : document.getElementById('subject-input').value,
            grade:getOptionText('grade-select'),
            day:document.getElementById('validity-select').value,
            type:document.getElementById('type-select').value
          }
          const response = await fetch('/save_questions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(saveData)
          });
          const result = await response.json();

          if (result.success){
            alert(`已成功将试题保存到题库！\n学科：${document.getElementById('subject-input').value}\n年级：${getOptionText('grade-select')}\n天数：${document.getElementById('validity-select').value}\n类型：${document.getElementById('type-select').value}`);
          }
          else {
            alert('保存出现错误')
          }

            // 关闭弹窗
            closeModal();
        });

        // 辅助函数：根据select的id获取选中选项的文本
        const getOptionText = (selectId) => {
            const select = document.getElementById(selectId);
            return select.options[select.selectedIndex].text;
        };
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        console.log('页面加载完成，开始初始化...'); // 调试日志

        setupRoleSwitch();
        setupModeSwitch();
        setupQuantityControls();
        setupPdfUpload();
        setupExamImport();
        setupGenerateButton();
        setupSaveToBankModal();
        setupClearAll();
        setupDeleteButtons();

        console.log('所有初始化完成'); // 调试日志
    });
</script>
</body>
</html>